package cpu.footprint.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cpu.footprint.R;
import cpu.footprint.adapter.CommonAdapter;
import cpu.footprint.adapter.ViewHolder;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.MyApplication;
import cpu.footprint.bean.Active;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.util.FileUtil;
import cpu.footprint.view.photo.TouchImageActivity;

import static cpu.footprint.api.ApiUrl.URL_FILEPATH;

/**
 * Created by WJP on 2017/3/14.
 */
@ContentView(value = R.layout.activity_activedetail)
public class ActiveDetailActivty extends BaseActivity {
    private String TAG = "ActiveDetailActivty";
    @ViewInject(R.id.title_content)
    private TextView title_content;//title内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//title功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//title功能
    @ViewInject(R.id.text_name)
    private TextView text_name;//活动名称
    @ViewInject(R.id.text_createNickName)
    private TextView text_createNickName;//创建人昵称
    @ViewInject(R.id.text_collectionSite)
    private TextView text_collectionSite;//集合地点
    @ViewInject(R.id.text_activitySite)
    private TextView text_activitySite;//活动地点
    @ViewInject(R.id.text_act_date)
    private TextView text_act_date;//活动时间
    @ViewInject(R.id.text_groupNumber)
    private TextView text_groupNumber;//活动群
    @ViewInject(R.id.text_description)
    private TextView text_description;//活动简介
    @ViewInject(R.id.btn_applyJoin)
    private Button btn_applyJoin;
    private User user = new User();
    private MyApplication myApplication;
    private String mMobilePhone;
    private Double activityLongitude;
    private Double activityLatitude;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
    private Dialog mDialog;
    @ViewInject(R.id.layout_activeimages)
    private GridView layout_images;
    private ArrayList<String> imgPaths = new ArrayList<>();//图片路径
    private CommonAdapter<String> imageAdapter;
    private boolean joined = false;//已经加入

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myApplication = (MyApplication) getApplication();
        if(myApplication.isLogin()) {
            user = myApplication.getUser();
        }
        Active active = (Active) this.getIntent().getSerializableExtra("active");
        joined = this.getIntent().getBooleanExtra("joined", false);
        initView(active);
        initData(active);
    }

    @Event(value = {R.id.title_back, R.id.image_call, R.id.image_position,R.id.btn_applyJoin})
    private void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back: {
                ActiveDetailActivty.this.finish();
                overridePendingTransition(0, R.anim.fade);
            }
            break;
            case R.id.image_call: {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.CALL");
                intent.addCategory("android.intent.category.DEFAULT");
                //指定要拨打的电话号码
                intent.setData(Uri.parse("tel:" + mMobilePhone));
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(ActiveDetailActivty.this, "没有打开拨号权限！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(intent);
            }
            break;
            case R.id.image_position: {
                Intent intent = new Intent();
                intent.putExtra("activityLatitude", activityLatitude);
                intent.putExtra("activityLongitude", activityLongitude);
                setResult(2, intent);
                ActiveDetailActivty.this.finish();
                overridePendingTransition(0, R.anim.fade);
            }
            break;
            case R.id.btn_applyJoin: {
                if(!myApplication.isLogin()){
                    Toast("请先登录");
                }
            }
            break;
            default:
                break;
        }
    }

    /**
     * 初始化数据
     */
    private void initData(Active model) {
        try {
            mMobilePhone = model.getUser().getMobilePhone();
        } catch (Exception e) {
            e.printStackTrace();
        }
        activityLongitude = model.getActivityLongitude();
        activityLatitude = model.getActivityLatitude();
        text_name.setText(model.getName());
        text_activitySite.setText(model.getActivitySite());
        text_createNickName.setText(model.getUser().getNickName());
        text_groupNumber.setText(model.getGroup().getId());
        text_collectionSite.setText(model.getCollectionSite());
        text_act_date.setText(sdf.format(model.getBeginTime()) + " - " + sdf.format(model.getEndTime()));
        String description = model.getDescription();
        if (description != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(description);
            description = m.replaceAll("");
        }
        text_description.setText("\u3000\u3000" + description);//首行缩进
        String imagePaths = model.getImagePaths();
        imagePaths.replaceAll(" ", "");
        String[] imgs = imagePaths.split(";");
        imgPaths.clear();
        for (int i = 0; i < imgs.length; i++) {
            imgPaths.add(ApiUrl.URL_HOST + imgs[i]);
        }
        imageAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化布局
     *
     * @param active
     */
    private void initView(Active active) {
        title_content.setText("活动详情");
        title_menu_image.setVisibility(View.GONE);
        title_menu_text.setVisibility(View.GONE);
        mDialog = showLoadingDialog(this);
        initAdapter();
        if (user.getCurrentlyActiveId() != null && (active.getId() == user.getCurrentlyActiveId() || active.getUser().getId() == user.getId())) {
            joined = true;
        }
        if (joined) {
            btn_applyJoin.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化图片适配器
     */
    private void initAdapter() {
        imageAdapter = new CommonAdapter<String>(this, imgPaths, R.layout.active_imgitem) {
            @Override
            public void convert(ViewHolder helper, final String item, int position) {
                ImageView imageView = helper.getView(R.id.image);
                final String fileName = URL_FILEPATH + FileUtil.getInstance().getImageName(item);
                final int index = position;
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ActiveDetailActivty.this, TouchImageActivity.class);
                        intent.putExtra("index", index);
                        intent.putStringArrayListExtra("imgs", imgPaths);
                        startActivity(intent);
                        overridePendingTransition(0, R.anim.fade);
                    }
                });
                if (FileUtil.fileIsExists(fileName)) {
                    Uri uri = Uri.fromFile(new File(fileName));
                    imageView.setImageURI(uri);
                } else {
                    Picasso.with(ActiveDetailActivty.this).load(item).placeholder(R.mipmap.defaultpicture).into(imageView);
                }
            }
        };
        layout_images.setAdapter(imageAdapter);
        imageAdapter.notifyDataSetChanged();
    }

    /**
     * 重写后退函数
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            ActiveDetailActivty.this.finish();
            overridePendingTransition(0, R.anim.fade);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }
}
